﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Linq;
using System;

using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using LmgCMS.Model;
using Newtonsoft.Json.Linq;
using LmgCMS.Service;

//https://gitee.com/Lancc/NETCore3WebAPI_Swagger_Jwt/tree/master/JWT_Swagger_CoreAPI/Controllers
namespace LmgCMS.Areas.API.Controllers
{
    /// <summary>
    /// 授权
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    [ApiExplorerSettings(GroupName = SwaggerGroupingModel.GROUPNAME_COMM)]
    public class AuthController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IRoleService _roleService;
        private readonly IRelevanceService _relevanceService;
        private readonly ApplicationSettings _applicationSettings;
        public AuthController(IUserService userService,
            IRoleService roleService,
            IRelevanceService relevanceService, ApplicationSettings applicationSettings)
        {
            _userService = userService;
            _roleService = roleService;
            _relevanceService = relevanceService;
            _applicationSettings = applicationSettings;
        }
        [AllowAnonymous]
        [HttpGet]
        public IActionResult NoPermission()
        {
            return Forbid("No Permission!");
        }
        /// <summary>
        /// 客户端获取Token
        /// </summary>
        /// <param name="request">输入账号密码</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Gettoken([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("Invalid Request");
            }
            string username = request.LoginID;
            string password = request.LoginPwd;
            TokenModelJwt jwt = new TokenModelJwt();
            jwt.UserId = request.LoginID;
            try
            {
                if (request.LoginID == "admin")
                {
                    string pwd = AppConfig.AdminPwd;
                    if (password == pwd)
                    {
                        HttpContext.Session.SetString("UserName", "admin");
                        HttpContext.Session.SetString("UserNum", "admin");
                        jwt.UserName = "admin";
                        jwt.Phone = "13320163492";
                        jwt.Email = "minguiluo@163.com";
                        jwt.TenantId = "";
                    }
                    else
                    {
                        return Content(ShowMessage.Error("用户名或密码不正确,请联系管理员。"));
                    }
                }
                else
                {
                    var user = _userService.GetByName(username);
                    if (user != null)
                    {
                        if (user.Password == request.LoginPwd)
                        {
                            jwt.UserName = user.Name;
                            jwt.Phone = user.Mobile;
                            jwt.Email = user.Email;
                            jwt.TenantId = user.TenantId;
                        }
                        else
                        {
                            return Content(ShowMessage.Error("登录密码不正确,请联系管理员。"));
                        }
                    }
                    else
                    {
                        return Content(ShowMessage.Error(request.LoginID + "登录名不存在,请联系管理员。"));
                    }
                }
                var jwtToken = JwtHelper.CreateToken(jwt);
                return Content(ShowMessage.Success("登录成功,正在跳转请稍候...", jwtToken));
            }
            catch (Exception ex)
            {
                return Content(ShowMessage.Error("登录失败：" + ex.Message));
            }
        }
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetCurUser()
        {
            //获取JWT
            string AuthorizationToken = HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (string.IsNullOrWhiteSpace(AuthorizationToken))
            {
                return BadRequest("Invalid Request Headers Authorization");
            }
            string JwtToken = AuthorizationToken.Split(' ')[1];
            //解析JWT中的用户信息
            var jwtToken = JwtHelper.SerializeJwt(JwtToken);
            return Ok(jwtToken);
        }
        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        //[HttpGet]
        //public ActionResult Test()
        //{
        //    var table = DataAccess.CreateBase_User().GetList("");
        //    return Ok(table.ToJson());
        //}
    }
}
